package com.terren.webdig.common.interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.terren.webdig.common.annotation.AuthLoginAnnotation;
import com.terren.webdig.common.config.ConfigInfo;

/**
 * 登录拦截
 * 
 * @author admin
 *
 */
public class SystemInitInterceptor extends HandlerInterceptorAdapter {

	//private List<String> IGNORE_URI;
	private static final String AJAX_TIME_OUT  = "ajaxSessionTimeOut";
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// 获取URI后缀
		/*String requestUri = request.getServletPath();
		if (requestUri.equalsIgnoreCase("/"))
			return true;
		// 过滤不需要拦截的地址
		for (String uri : IGNORE_URI) {
			if (requestUri.startsWith(uri)) {
				return true;
			}
		}*/
		HandlerMethod methodHandler= (HandlerMethod)handler;
        AuthLoginAnnotation annotation = methodHandler.getMethodAnnotation(AuthLoginAnnotation.class);
        if(null!=annotation&&!annotation.check()){
        	return true;
        }
		HttpSession session = request.getSession();
		if (session != null && session.getAttribute(ConfigInfo.SESSION_USER) != null) {
			return true;
		} else {
			if (isAjaxRequest(request)) {
				PrintWriter printWriter = response.getWriter();   
				printWriter.print(AJAX_TIME_OUT);                    
				printWriter.flush();    
				printWriter.close(); 
				return false;
			}
			response.sendRedirect(request.getContextPath() + "/user/userLogin");
			return false;
		}
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}
	private boolean isAjaxRequest(HttpServletRequest request) {  
        String header = request.getHeader("X-Requested-With");  
        if (header != null && "XMLHttpRequest".equals(header))  
            return true;  
        else  
            return false;  
    }
	/*public List<String> getIGNORE_URI() {
		return IGNORE_URI;
	}

	public void setIGNORE_URI(List<String> iGNORE_URI) {
		IGNORE_URI = iGNORE_URI;
	}*/
	
}
